/**
 * @file 设备列表插件
 */
import treeMenu from '@/components/Menu/menu.vue';
import $ from 'jquery';
export default {
    components: {
        treeMenu
    },
    props: {
        topTilte: {            // 标题
            type: String,
            default: ''
        },
        subTitle: {        // 当需要选择设备控制项时，右侧标题，此时showSetParm必须传true
            type: String,
            default: 'equipSelect.subTitle[0]'
        },
        selectedChange: {    // 当点击确定时传所选设备
            type: Function,
            default: () => { }
        },
        selectedMode: {      // 模式选择，1为单选，0为多选
            type: Number,
            default: 0
        },
        showInput: {
            type: Boolean,
            default: true
        },
        showDatePicker: {
            type: Boolean,
            default: false
        },
        equipSelected: {      // 已选择的设备
            type: Array,
            default: () => []
        },
        showSetParm: {       // 是否需要选择设备控制项
            type: Boolean,
            default: false
        },
        confirmButton: {
            type: String,
            default: '确定'  // 确定按钮显示文字（确定，导出、、、等按钮）
        },
        exportLoading: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            equipLoading: false, // 设备加载loading
            equipList: [], // 设备列表
            searchName: '', // 搜索框
            selectedList: [],
            total: 10,
            currentPage: 1,
            pageSize: 5,
            dialogVisible: true,
            equipNo: -1,
            setParmList: [],
            setParmCurrentPage: 1,
            setParmPageSize: 8,
            setParmTotal: 0,
            setParmCurrentIndex: -1,
            setParmData: {
                setNo: -1,
                setName: ''
            },
            dateTime: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
            ECStartTime: '',    // 导出曲线开始时间
            ECEndTime: '',        // 导出曲线结束时间
            ycpSearch: '',
            yxpSearch: '',
            ycpAllSelect: false,
            yxpAllSelect: false,
            ycList: [],
            yxList: [],
            equipsList: [],
            ycSelect: [],
            yxSelect: [],
            pickerOptions: {
                disabledDate (time) {
                    return time.getTime() > new Date() - 24 * 60 * 60 * 1000;
                }
            },
            getYxYcLoading: false

        };
    },
    computed: {
        // ycps () {
        //     let names = new Set();
        //     this.getYxYcLoading = true
        //     for (let item of this.ycList) {
        //         if (this.ycpSearch) {
        //             if (item.ycName.indexOf(this.ycpSearch) != -1) {
        //                 names.add(item.ycName)
        //             }
        //         } else {
        //             names.add(item.ycName)
        //         }
        //     }

        //     if (this.ycSelect.length > 0 && names.length > 0 && this.isContained(this.ycSelect, names)) {
        //         this.ycpAllSelect = true
        //     } else {
        //         this.ycpAllSelect = false
        //     }
        //     this.getYxYcLoading = false
        //     return names
        // },
        ycps () {
            let names = [];
            for (let item of this.ycList) {
                if (names.indexOf(item.ycName) == -1) {
                    if (this.ycpSearch) {
                        if (item.ycName.indexOf(this.ycpSearch) != -1) {
                            names.push(item.ycName)
                        }
                    } else {
                        names.push(item.ycName)
                    }
                }
            }

            if (this.ycSelect.length > 0 && names.length > 0 && this.isContained(this.ycSelect, names)) {
                this.ycpAllSelect = true
            } else {
                this.ycpAllSelect = false
            }
            return names
        },
        yxps () {
            let names = [];
            for (let item of this.yxList) {
                if (names.indexOf(item.yxName) == -1) {
                    if (this.yxpSearch) {
                        if (item.yxName.indexOf(this.yxpSearch) != -1) {
                            names.push(item.yxName)
                        }
                    } else {
                        names.push(item.yxName)
                    }
                }
            }

            if (this.yxSelect.length > 0 && names.length > 0 && this.isContained(this.yxSelect, names)) {
                this.yxpAllSelect = true
            } else {
                this.yxpAllSelect = false
            }
            return names
        }
    },
    mounted () {

        this.ECStartTime = this.$moment().subtract(1, 'days')
            .startOf('day')
            .format('YYYY-MM-DD HH:mm:ss');
        this.ECEndTime = this.$moment().subtract(1, 'days')
            .endOf('day')
            .format('YYYY-MM-DD HH:mm:ss');

        // 缓存 ，搜索用API请求
        this.equipLoading = true;
        // if (this.globalVariable.initsEquipAList.groups && !this.globalVariable.search) {
        //     setTimeout(() => {
        //         this.equipLoading = false;
        //         this.equipList = this.globalVariable.initsEquipAList.groups;
        //     }, 500);
        // } else {
        //     this.searchEquips();
        // }
        this.searchEquips();
        if (this.showSetParm) {
            $('.menuDialog .equipSelect').addClass('showSetParm');
        }
    },
    methods: {

        // 判断是否包含  a是否包含b
        isContained (a, b) {
            if (!(a instanceof Array) || !(b instanceof Array)) return false;
            if (a.length < b.length) return false;
            let aStr = a.toString();
            for (let i = 0, len = b.length; i < len; i++) {
                if (aStr.indexOf(b[i]) == -1) return false
            }
            return true
        },
        // ycSelectChange (name) {
        //     console.log(8888);
        //     let index = this.ycSelect.indexOf(name)
        //     if (index == -1) {
        //         this.ycSelect.push(name)
        //         console.log(this.ycSelect.length, this.ycList.length);
        //         if (this.ycSelect.length == this.ycList.length) {
        //             this.ycpAllSelect = true

        //         }
        //     } else {
        //         this.ycSelect.splice(index, 1)
        //         this.ycpAllSelect = false
        //     }

        //     // console.log(this.ycpAllSelect);
        //     this.$forceUpdate()
        // },

        ycSelectChange (name) {
            let index = this.ycSelect.indexOf(name)
            if (index == -1) {
                this.ycSelect.push(name);
                if (this.ycSelect.length == this.ycList.length) {
                    this.ycpAllSelect = true
                }
            } else {
                this.ycSelect.splice(index, 1)
                this.ycpAllSelect = false
            }
        },

        yxSelectChange (name) {
            let index = this.yxSelect.indexOf(name)
            if (index == -1) {
                this.yxSelect.push(name);
                if (this.yxSelect.length == this.yxList.length) {
                    this.yxpAllSelect = true
                }
            } else {
                this.yxSelect.splice(index, 1)
                this.yxpAllSelect = false
            }
        },

        radioCheck (equips, equipNo, isNoCheck) {
            if (equipNo) {
                let index = equips.indexOf(equipNo)
                if (index != -1) {
                    if (isNoCheck) {
                        equips.splice(index, 1)
                    }
                } else {
                    if (!isNoCheck) {
                        equips.push(equipNo)
                    }
                }
            }
            this.equipsList = JSON.parse(JSON.stringify(equips))
            this.$api.getYcpsYxps({ equipNos: equips }).then(res => {
                if (res.data.code == 200) {
                    let ycps = res.data.data.ycps;
                    let yxps = res.data.data.yxps;
                    if (ycps && ycps.length >= 0) {
                        this.ycList = ycps
                    }
                    if (yxps && yxps.length >= 0) {
                        this.yxList = yxps
                    }
                } else {
                    this.yxList = [];
                    this.ycList = []
                }
            }).catch(err => {
                this.yxList = [];
                this.ycList = []
                console.log(err);
            })
        },
        changeAllSelect (dt, value, type) {
            let isNoCheck = $(dt.target).hasClass('checkInput-active');
            if (type == 'yc') {
                if (this.ycList && this.ycList.length == 0) {
                    this.$message.warning(this.$t('equipSelect.warnings[0]'))
                    return;
                }
                if (isNoCheck) {
                    this.ycSelect = [];
                } else {
                    this.ycSelect = [];
                    this.ycSelect = [...this.ycps]
                }

            } else {
                if (this.yxList && this.yxList.length == 0) {
                    this.$message.warning(this.$t('equipSelect.warnings[0]'))
                    return;
                }
                if (isNoCheck) {
                    this.yxSelect = [];
                } else {
                    this.yxSelect = [];
                    this.yxSelect = [...this.yxps]
                }

            }
            if (isNoCheck) {
                $(dt.target).removeClass('checkInput-active');
                this[value] = false
            } else {
                $(dt.target).addClass('checkInput-active');
                this[value] = true
            }
        },
        setParmHandleChange (val) {
            this.setParmCurrentPage = val;
            this.getItem();
        },
        getItem (item, isNoCheck) {
            console.log(item);

            // 当需要选择设备控制项的时候传equipNo
            this.radioCheck(this.equipsList, item.equipNo, isNoCheck)
        },
        selectedSetParm (item) {
            this.setParmCurrentIndex = item.setNo;
            this.setParmData.setNo = item.setNo;
            this.setParmData.setName = item.setNm;
        },
        sendData () {
            let ycArr = this.ycList.filter(item => {
                return this.ycSelect.indexOf(item.ycName) != -1
            })
            let yxArr = this.yxList.filter(item => {
                return this.yxSelect.indexOf(item.yxName) != -1
            })

            // 根据设备号进行分组
            let map = {};
            let res = [];
            if (ycArr && ycArr.length > 0) {
                for (let index = 0, length = ycArr.length; index < length; index++) {
                    let ai = ycArr[index];
                    if (!map[ai.equipNo]) {
                        map[ai.equipNo] = {}
                        map[ai.equipNo]['ycps'] = [ai.ycNo]
                        map[ai.equipNo]['staNo'] = ai.staNo
                    } else {
                        map[ai.equipNo]['ycps'].push(ai.ycNo)
                    }
                }

                Object.keys(map).forEach(key => {
                    let yxps = []
                    for (let index = 0, length = yxArr.length; index < length; index++) {
                        if (yxArr[index].equipNo == Number(key)) {
                            yxps.push(yxArr[index].yxNo)
                        }
                    }
                    res.push({
                        equipNo: Number(key),
                        ycps: map[key]['ycps'],
                        staNo: map[key]['staNo'],
                        yxps: yxps
                    })
                })
            } else {
                for (let index = 0, length = yxArr.length; index < length; index++) {
                    let ai = yxArr[index];
                    if (!map[ai.equipNo]) {
                        map[ai.equipNo] = {}
                        map[ai.equipNo]['yxps'] = [ai.yxNo]
                        map[ai.equipNo]['staNo'] = ai.staNo
                    } else {
                        map[ai.equipNo]['yxps'].push(ai.yxNo)
                    }
                }

                Object.keys(map).forEach(key => {
                    res.push({
                        equipNo: Number(key),
                        yxps: map[key]['yxps'],
                        staNo: map[key]['staNo'],
                        ycps: []
                    })
                })
            }

            let data = {
                beginTime: this.ECStartTime ? this.$moment(this.ECStartTime).format('YYYY-MM-DD HH:mm:ss').split(' ').join('T') : '',
                endTime: this.ECEndTime ? this.$moment(this.ECEndTime).format('YYYY-MM-DD HH:mm:ss').split(' ').join('T') : '',
                exportEquips: res,
                equipsList: this.equipsList
            }
            this.selectedChange(data)
        },

        // sendData () {
        //     let equipNoList = [];
        //     if (this.selectedMode === 0) {
        //         let dataList = $('.child_tags');
        //         dataList.each((item) => {
        //             if (
        //                 $($('.child_tags')[item])
        //                     .children('label')
        //                     .hasClass('checkInput-active')
        //             ) {
        //                 if (
        //                     $($('.child_tags')[item])
        //                         .children('label')
        //                         .attr('no') !== 0
        //                 ) {
        //                     equipNoList.push({
        //                         equipNo: parseInt(
        //                             $($('.child_tags')[item])
        //                                 .children('label')
        //                                 .attr('no'),
        //                             10
        //                         ),
        //                         equipName: $($('.child_tags')[item])
        //                             .children('a')
        //                             .text().trim(),
        //                         staNo: parseInt(
        //                             $($('.child_tags')[item])
        //                                 .children('label')
        //                                 .attr('staNo'),
        //                             10
        //                         )
        //                     });
        //                 }
        //             }
        //         });
        //     } else if ($('.selectedColor')) {
        //         if ($('.selectedColor').length > 0) {
        //             equipNoList.push({
        //                 equipName: $('.selectedColor')
        //                     .children('a')
        //                     .text().trim(),
        //                 equipNo: parseInt($('.selectedColor').attr('equipno'), 10),
        //                 staNo: parseInt(
        //                     $($('.child_tags')[item])
        //                         .children('label')
        //                         .attr('staNo'),
        //                     10
        //                 )
        //             });
        //         }
        //     }
        //     if (equipNoList.length === 0) {
        //         this.$message({
        //             message: this.$t('equipSelect.tips[0]'),
        //             type: 'warning'
        //         });
        //     } else if (this.showSetParm && this.setParmData.setNo === -1) {
        //         this.$message({
        //             message: this.$t('equipSelect.tips[1]'),
        //             type: 'warning'
        //         });
        //     } else {
        //         this.filterData(equipNoList);
        //     }
        // },
        filterData (data) {
            let Arr = [];
            let ArrList = [];
            data.forEach((item) => {
                if (Arr.indexOf(item.equipNo) === -1) {
                    Arr.push(item.equipNo);
                    ArrList.push(item);
                }
            });
            if (this.showSetParm) {
                this.selectedChange(ArrList, this.setParmData);
            } else if (this.showDatePicker) {
                this.selectedChange(ArrList, this.$moment(this.ECStartTime).format('YYYY-MM-DD HH:mm:ss'), this.$moment(this.ECEndTime).format('YYYY-MM-DD HH:mm:ss'));
            } else {
                this.selectedChange(ArrList);
            }
        },
        handleCurrentChange (val) {
            this.currentPage = val;
            this.searchEquips();
        },

        // onSearch () {
        //     this.searchEquips();
        //     this.globalVariable.search = true;
        // },

        // 获取左侧设备列表
        searchEquips () {
            let data = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                SearchName: this.searchName
            };
            this.equipLoading = true;
            this.$api
                .GroupListNoState(data)
                .then((rt) => {

                    // 搜索请求结果
                    if (rt.data.message === '无查找结果') {
                        this.equipList = [];
                        return;
                    }
                    if (rt.data.code === 200) {
                        this.equipList = rt.data.data.groups;
                        this.total = rt.data.data.groups.length;
                        // if (!this.globalVariable.search) {
                        //     this.globalVariable.initsEquipAList = rt.data.data;
                        // }
                        if (this.searchName.length === 0) {
                            this.globalVariable.search = false;
                        }
                    }
                    this.equipLoading = false;
                })
                .catch((err) => {
                    this.equipLoading = false;
                    console.log('err---', err);
                });

        }
    }
};